<template>
	<div class="mainCon">
		<div class="penalrow selectw100">
			<div class="inlineblock verticalmiddle infoitem">
				<div class="inlineblock verticalmiddle">
				应用名称
				</div>
				<div class="inlineblock verticalmiddle" style="margin-left: 15px;">
					<el-select v-model="appvalue" placeholder="请选择" size="mini">
						<el-option
							v-for="item in appData"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
				</div>
				
			</div>
				<div class="basicRightDistanceA" style="position:absolute;">
				
				<el-button type="primary" size="mini" @click="addmenu({isAdd: true})">新增</el-button>
			</div>
		</div>
		
		<div class="treeparent">
			<div class="inlineblock  tree">
				<el-tree :data="treedata" :props="defaultProps" @node-click="handleNodeClick"  ref="treeBox"  node-key='id' :default-checked-keys="arrHight" :highlight-current='true'  :expand-on-click-node="false" ></el-tree>
			</div>
			<div class="inlineblock treeright" style="margin-top: 0;">
				<div class="separaterow" style="margin-top: 0;height:100%;">
					<el-table :data="menuData"
						:default-sort = "{prop: 'morder', order: 'ascending'}"
						 style="height: 100%;"  size="mini" highlight-current-row  border ref="standardTable">
						
						<el-table-column property="name" label="名称"  min-width="60px">
						</el-table-column>
						<el-table-column property="pageAddress" label="地址"  min-width="180px">
						</el-table-column>
						<el-table-column  label="排序" min-width="60px" sortable property="morder">
						</el-table-column>
						<!--<el-table-column
			                property="status"
			                label="状态"
			                min-width="120px"
			                :formatter="formatter"
			                >
			              </el-table-column>-->
						
						<el-table-column property="operation" label="操作" min-width="60px">
							<template slot-scope="scope">
			                  <el-button  type="text" size="mini" @click.native="addmenu({index:scope.$index, row:scope.row,isAdd: false})">编辑</el-button>
			                  <el-button type="text" size="mini" @click.native="handleDelete(scope.$index, scope.row)">删除</el-button>
			                </template>
						</el-table-column>
					</el-table>
					
				</div>
		
			</div>
		</div>
		<div class="popupMask" v-if="dialogVisible">
			<div class="popupPenal">
				<div class="popPenalTitle">
					<div class="popPenalTitleName">
						菜单管理
					</div>
					<div class="popupClose ensure">
						
						<el-button  type="primary" size="mini" @click="submitForm('menuForm')">保存</el-button>
					</div>
					<div class="popupClose">
						<el-button size="mini" @click="resetForm('menuForm')">关闭</el-button>
					</div>
				</div>
				<div class="penalContent" style="padding: 30px;">
						<el-form label-width="110px" class="demo-ruleForm" :model="menuForm" :rules="rules" ref="menuForm" >
						  	<el-form-item label="名称" prop="name" >
								<el-col :span="15">
									<el-input  placeholder="名称" v-model="menuForm.name"></el-input>
					
								</el-col>
							</el-form-item>
							<el-form-item label="地址" prop="pageAddress" >
								<el-col :span="15">
									<el-input  placeholder="如:/menu" v-model="menuForm.pageAddress"></el-input>
					
								</el-col>
							</el-form-item>
							<el-form-item label="排序"  prop="morder">
								<el-col :span="15">
									<el-input  placeholder="排序" v-model="menuForm.morder"></el-input>
								</el-col>
							</el-form-item>
							<!--<el-form-item label="状态" >
								<el-col :span="15">
									<el-select v-model="menuForm.status" placeholder="请选择" style="width: 100%;" >
										<el-option v-for="item in statusoptions" 
											:key="item.value" 
											:label="item.label" 
											:value="item.value">
										</el-option>
									</el-select>
								</el-col>
							</el-form-item>-->
							<el-form-item label="操作项"  prop="operation">
								<el-col :span="15">
									<el-checkbox-group v-model="menuForm.operation" @change = "changeItem">
										<el-checkbox 
											v-for="city in operationstaus" 
											:label="city" 
											:key="city.id"
											:value="city.id">{{city.name}}
										</el-checkbox>
									</el-checkbox-group>
								</el-col>
							</el-form-item>
					 </el-form>
				
					
				</div>
				<div class="penalFooter" v-if="!isaddmenu">
					<p><span>创建人 : </span><span>{{menuForm.createBy}}</span></p>
					<p><span>创建时间 :</span><span>{{menuForm.createTime}}</span></p>
					<p v-if="menuForm.updateBy != undefined"><span>修改人 : </span><span>{{menuForm.updateBy}}</span></p>
					<p v-if="menuForm.updateTime != undefined"><span>修改时间 : </span><span>{{menuForm.updateTime}}</span></p>
				</div>
			</div>
		</div>
		
	</div>
</template>

<script>
	import deleteConfirm from '@/common/deleteConfirm.vue';
	const options = [];
	export default {
		data() {
			return {
				dialogVisible: false, //表单弹出控制
				deleteConfirmShow:false,
				isaddmenu:false, //是否是新增菜单
				appData: [],
		        appvalue: '',
		        treedata: [],
			    defaultProps: {
			        children: 'sub',
			        label: 'name'
			    },
			    menuData:[],
       			operationstaus:null,
       			selectedMenu:false, //是否选中左边菜单
       			firstRander:true, //是第一次渲染
       			sendData:{
       				parentId:'',
		    		appid:'',
       			},
       			statusoptions:[
       				{
						value: 1,
						label: '停用'
					},
					{
						value: 2,
						label: '启用'
					}
       			],
       			menuForm:{
       				name :'',
       				operation:[],
       				pageAddress:'',
       				morder:'',
       				status:2,
       			},
       			arr: [],
       			arrHight:[],
       			rules:{
       				name:[
						{required: true,type: 'string',  message: '请填写名称', trigger: 'blur' },
					],
//					pageAddress:[{required: true,type: 'string',  message: '请填写地址', trigger: 'blur' },
//						{ required: true,validator:(rule, value, callback) => {
//							 //由英文数字斜线组成
////							 ~ m!^(.*)/([^/]*)$!
////							var reg = /^(/w+(-/w+)*)(/.(/w+(-/w+)*))*(/?/S*)?$/;  
////	                        var reg = /^[a-z][A-Z][0-9]\/\*\.[a-z]$/;
//					        if (value == '') {
//					          	callback(new Error('请填写地址'));
//					        } else if (!reg.test(value)) {
//				        	 	callback(new Error('地址格式不正确'));
//					        } else {
//				         	 	callback();
//					        }
//					      },trigger: 'blur', },
//					]
       			},
				selectItem:[],
			};
		},
		mounted(){
			this.getAppData();
			this.getModelByAppid(this.appvalue);
			
		},
		methods: {
			formatter(row, column) {
				if(row.status == 1){
					var newType = '停用'
				}else if(row.status == 2){
					var newType = '启用'
				}
		        return newType;
		    },
			//获取应用名称
			getAppData(){
				this.$http({
					method: 'get', 
					apiUrl: 'systemmanage/getAppList.htm',
				}).then(res=>{
					if(res.code == 0){
						this.appvalue = res.data[0].id;
						this.appData = res.data;
					}
				})
			},
			//获取左边菜单树
			getModelByAppid(appid,nid){
				if(appid){
					this.$http({
						method: 'get', 
						apiUrl: 'systemmanage/selSysModelByAppid.htm',
						params: {appid :appid},
						isJson:true,
					}).then(res=>{
						if(res.code === 0){
								let setting={
								id:"id",
								pid:"parent",
								root:"",
								data:res.data
							};
							this.treedata = this.$listtotree(setting);
							if(nid){
								this.arrHight.push(nid);
								this.$nextTick(() => {
									 this.$refs.treeBox.setCurrentKey(nid);// treeBox 元素的ref   value 绑定的node-key
								});
							}
							this.$nextTick(() => {
								if(this.treedata.length > 0){
									this.$refs.treeBox.store.nodesMap[this.treedata[0].id].expanded = true;
									
								}
							})
						}
						
					})
				}
				
			},
			//点击节点
		    handleNodeClick(data) {
		    	this.selectedMenu = true;
		    	this.sendData.parentId = data.parent;
			    this.sendData.appid = this.appvalue;
			    this.sendData.modelId = data.id;
		    	if(data.name == "全部" || data.id=='root'){
		    		this.$http({
						method: 'get', 
						apiUrl: 'systemmanage/getModuleListByRoot.htm',
					}).then(res=>{
						if(res.code == 0){
							this.menuData = res.data;
						}
						
					})
		    	}else{
			    	this.$http({
						method: 'get', 
						apiUrl: 'systemmanage/getModuleListByParentTwo.htm',
						params: {
							modelId:data.id
						},
						isJson:false
					}).then(res=>{
						if(res.code == 0){
							this.menuData = res.data;
						}
						
					})
					
		    	}
		    	
		   },
		   //添加菜单出现
		   	addmenu(obj){
		   		if(obj.isAdd){
		   			this.isaddmenu = true;
		   			if(this.selectedMenu){
						if(this.firstRander){
				   			this.$http({
								method: 'get', 
								apiUrl: 'systemmanage/selOperationList.htm'
							}).then(res=>{
								if(res.code === 0){
									options.splice(0);
									for(var i in res.data){
										this.$set(options,i,JSON.parse(JSON.stringify(res.data[i])))
									}
						   			this.operationstaus = options;
								}
							})
				   		}
				   		this.dialogVisible = true;
			   			
			   		}
		   		}else{

		   			this.dialogVisible = true;
		   			this.isaddmenu = false;
		   			for(var i in obj.row){	//赋值
						this.menuForm[i] = obj.row[i]
					}
		   			console.log(this.menuForm)
//		   			if(this.firstRander){
						this.arr   = []
			   			this.$http({
							method: 'get', 
							apiUrl: 'systemmanage/selOperationList.htm'
						}).then(res=>{
							if(res.code === 0){
								options.splice(0);
								for(var i in res.data){
									this.$set(options,i,JSON.parse(JSON.stringify(res.data[i])))
									this.$set(this.arr,i,JSON.parse(JSON.stringify(res.data[i])))
									
								}
								this.$http({
									method: 'get', 
									apiUrl: 'systemmanage/getModuleAndOpration.htm',
									params:{modelId:obj.row.id},
									isJson:false
								}).then(res=>{
									this.selectItem = JSON.parse(JSON.stringify(res.data[0].operList))
									//obj.row 重新赋值
									for(var i in res.data[0]){	
										obj.row[i] = res.data[0][i]
									}
									this.menuForm = {
					       				name :'',
					       				operation:[],
					       				pageAddress:'',
					       				morder:'',
					       				status:2,
					       			};
									for(var i in obj.row){	//赋值
										this.menuForm[i] = obj.row[i]
									}
									/*
								 * this.arr = [
								 * 	{code:'add',id:1,name:'新增'},
								 * 	{code:'update',id:2,name:'修改'}，
								 * 	{code:'delete',id:3,name:'删除'}，
								 * 	{code:'select',id：4,name:'查询'}
								 * ]
								 */
									for(var i of obj.row.operList){	//改变arr
										for(var j in this.arr){
											if(i.code == this.arr[j].code){
												this.arr.splice(j,1,i);
											}
										}
									}
									/*
									 *	obj.row.operList = 后台给你的，假设为{code：’delete‘，id:123456,name:'删除'}
									 * this.arr = [
									 * 	{code:'add',id:1,name:'新增'},
									 * 	{code:'update',id:2,name:'修改'}，
									 * 	{code:'delete',id:123456,name:'删除'}，
									 * 	{code:'select',id：4,name:'查询'}
									 * ]
									 */
									this.operationstaus = this.arr;
									this.menuForm.operation = [];
									for(var i in obj.row.operList){
										this.menuForm.operation[i] = obj.row.operList[i]; 
									}
									
									
	//					   			this.firstRander = false;
								})
								
							}
						})
		   		}
		   		
		   	},
			   
			changeItem(val){
				console.log(val)
				// 所有勾选的操作，数组
				
				

			},
		   	submitForm(ruleForm){
		   		this.$refs[ruleForm].validate((valid) => {  //表单验证
					if (valid) {
						debugger
						for(var i in this.menuForm.operation){
							this.menuForm.operation[i].id = '';
							for(var j in this.selectItem){ // 接口返回的勾选的
								if(this.menuForm.operation[i].code == this.selectItem[j].code){
									this.menuForm.operation[i].id = this.selectItem[j].id
								}
							}
						}

						if(this.isaddmenu){
							var url = 'systemmanage/addSysModel.htm';
							var data = {
								name :this.menuForm.name,
			       				appid:this.sendData.appid,
			       				parent:this.sendData.modelId,
			       				operList:this.menuForm.operation,
			       				pageAddress:this.menuForm.pageAddress,
			       				morder:this.menuForm.morder,
			       				status:this.menuForm.status,
							};
							this.$http({
								method: 'post',
								apiUrl: url,
								params: data,
								isJson:true,
							}).then(res=>{
								if(res.code == 0){
									this.$message({
										type: 'success',
										message: '提交成功!'
									});
									this.resetForm('menuForm');
									this.getModelByAppid(this.appvalue,this.sendData.modelId);
									this.handleNodeClick({id:this.sendData.modelId});
								}
								
							}).catch(() => {
								
							});
						}else{
							var url = 'systemmanage/updateSysModel.htm';
							var data = {
								id:this.menuForm.id,
								name :this.menuForm.name,
			       				appid:this.sendData.appid,
			       				operList:this.menuForm.operation,
			       				pageAddress:this.menuForm.pageAddress,
			       				morder:this.menuForm.morder,
			       				status:this.menuForm.status,
							};
							for(var i=0;i<data.operList.length;i++){
								if(data.operList[i].id == undefined){
									data.operList.splice(i,1)
								}
							}
							this.$http({
								method: 'post',
								apiUrl: url,
								params: data,
								isJson:true,
							}).then(res=>{
								if(res.code == 0){
									this.$message({
										type: 'success',
										message: '提交成功!'
									});
									this.resetForm('menuForm');
									this.getModelByAppid(this.appvalue,this.sendData.modelId);
									this.handleNodeClick({id:this.sendData.modelId});
									
								}
								
							}).catch(() => {
								
							});
						}
						
					}else{
						return false;
					}
				});
				
		   	},
			
			//删除
		    handleDelete(key,row){
		    	this.$confirm('是否删除', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				var that = this;
				var param = {
					modelId: row.id,
				}
				this.$http({
					apiUrl:'systemmanage/delSysModelById.htm',
					type: 'post',
					params: param,
				}).then(res =>{
					if(res.code === 0){
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.handleNodeClick({id:row.parent});
						this.getModelByAppid(this.appvalue,row.parent);
						
					}
				});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
//		      this.deleteConfirmShow = true;
		    },
			resetForm(formName) {	//重置表单,关闭表单

				this.$refs[formName].resetFields();//重置表单
				this.menuForm={
       				name :'',
       				operation:[],
       				pageAddress:'',
       				morder:'',
       			}
				this.dialogVisible = false;//关闭表单	
				
			},
		},
		components:{
			deleteConfirm
		},
		watch:{
			appvalue : {
		          handler(val, oldVal){
		            this.getModelByAppid(this.appvalue);
		            this.menuData = [];
		          },
		          deep:true
	        },
	       	
		}
	}
</script>

<style scoped>
	.v-modal{
		/*display: none;*/
	}
	.el-dialog__wrapper{ background-color:rgba(0,0,0,0.3) !important; }
	.el-dialog__header{
		height: 50px;
		line-height: 50px;
		padding: 0;
	}
	.treeparent {
		height: calc(100% - 50px);
		overflow: auto;
	}
	.tree {
		width: 23%;
		height: calc(100% - 10px);
		overflow: auto;
		background: #fff;
	}
	.treeright {
		margin-left: 10px;
		width: calc(76% - 10px);
		height: 100%;
		vertical-align: top;
	}
	.infoitem {
	width: calc(100%/2);
	padding-right: 20px;
	}
</style>